package de.gist.calldurationwatcher.helper;

import java.util.Date;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.CallLog;
import android.util.Log;

public class CallLogHelper {

	private final static String[] strFields = {
			CallLog.Calls.DATE,
			CallLog.Calls.CACHED_NAME,
			CallLog.Calls.DURATION,
			CallLog.Calls.NUMBER, 
	        CallLog.Calls.TYPE,
	        CallLog.Calls._ID };
	private final static String strOrder = CallLog.Calls.DATE + " DESC";
	
	public static Cursor getCallCursor(Context context) {
		
		if (context == null)
			return null;
		
		ContentResolver contentResolver = context.getContentResolver();
		if (contentResolver == null)
			return null;
		
		return internalGetContext(contentResolver, context);
	}
	
	public static Cursor getCallCursor(ContentResolver resolver, Context context) {
		
		if (resolver == null)
			return null;
		
		return internalGetContext(resolver, context);
	}
	
	private static Cursor internalGetContext(ContentResolver resolver, Context context) {
		
		Date filterDate = Utils.GetCallLogFilterDate(context);
		
		try {
			
			Cursor mCallCursor = resolver.query(
					CallLog.Calls.CONTENT_URI, 
					strFields,
					CallLog.Calls.DATE + ">=?", // Date filter "where date >= ?"
					new String[] { String.valueOf(filterDate.getTime())}, // get only last month
			        strOrder);
			
			return mCallCursor;
			
		} catch (Exception ex) {
			Log.d("CallLogHelper", ex.getMessage());
		}
		
		return null;
	}
}
